<template>
  <!-- 趋势对比  -  日期 -->

  <div class="date-box">
    <div v-if="echartShow">
      <div class="item-box">
        <div class="lt flex">
          <el-select v-model="checkedEO[0]" placeholder="请选择" size="small" class="select1" @change="handleDataChange">
            <el-option label="不显示" class="select1-op">
              <p>
                <i class="el-icon-check"></i>
                <span>不显示</span>
              </p>
            </el-option>
            <el-option
              v-for="(item,index) in echartsOptions"
              :key="index"
              :label="item.name"
              :value="item.val"
              :disabled="checkedEO[1]===item.val"
              class="select1-op"
            >
              <p>
                <i class="el-icon-check"></i>
                <span>{{ item.name }}</span>
              </p>
            </el-option>
          </el-select>
          <span>对比</span>
          <el-select v-model="checkedEO[1]" placeholder="请选择" size="small" class="select2" @change="handleDataChange">
            <el-option label="不显示" class="select2-op">
              <p>
                <i class="el-icon-check"></i>
                <span>不显示</span>
              </p>
            </el-option>
            <el-option
              v-for="(item,index) in echartsOptions"
              :key="index"
              :label="item.name"
              :value="item.val"
              :disabled="checkedEO[0]===item.val"
              class="select2-op"
            >
              <p>
                <i class="el-icon-check"></i>
                <span>{{ item.name }}</span>
              </p>
            </el-option>
          </el-select>

        </div>
        <div class="rt flex">
          <slot name="right" />
          <div class="handle-box flex" style="margin-left: 40px;">
            <i
              :class="dateEchartType=='line'?'iconfont icon-zhexiantu active':'iconfont icon-zhexiantu'"
              style="font-size: 18px;"
              @click="setEchartType('line')"
            />
            <i
              style="font-size: 18px;"
              :class="dateEchartType=='lineArea'?'iconfont icon-jurassic_broken-line active':'iconfont icon-jurassic_broken-line'"
              @click="setEchartType('lineArea')"
            />
            <i
              :class="dateEchartType=='bar'?'iconfont icon-zhuzhuangtu active':'iconfont icon-zhuzhuangtu'"
              style="font-size: 18px;"
              @click="setEchartType('bar')"
            />

            <i class="iconfont iconfont icon-xiazai" style="font-size: 18px;" @click="downloadImg" />
          </div>
        </div>
      </div>
      <div :id="idName" class="chart-table" :style="{height:height,width:'100%'}" />
    </div>
    <div v-else style="color: #909399;font-size: 14px;height: 236px;line-height: 236px;text-align: center;">暂无数据</div>
  </div>

</template>

<script>
import {
  echartsOptions
} from '@/settings.js'
import {
  colorList
} from '@/settings.js'

const grid = {
  top: '40px',
  left: '10px',
  right: '20px',
  bottom: '20px',
  containLabel: true
}

const yAxisItem = {
  type: 'value',
  min: 0,
  axisLine: {
    show: false
  },
  boundaryGap: true,
  axisTick: {
    show: false
  },
  nameTextStyle: {
    color: 'rgba(51, 64, 74, 0.8)',
    padding: [0, 5, 5, 0],
    fontSize: 12
  },
  axisLabel: {
    color: '#666',
    fontSize: 14
  }
}

import {
  mapGetters
} from 'vuex'
export default {
  props: {
    height: {
      default: '450px',
      type: String
    },
    idName: {
      default: function() {
        return 'dateEchart' + new Date().getTime()
      },
      type: String
    },
    dateInfo: {
      default: () => {
        return []
      },
      type: Object
    },
    unit: {
      type: String,
      default: function() {
        return this.$store.state.user.unit
      }
    },
    adchannelType: {
      type: String,
      default: () => {
        return 'SEARCH'
      }
    }
  },
  data() {
    return {
      echartShow: true,
      checkedEO: ['localSpendAmount', 'impressions'],
      dateEchart: undefined,
      dateEchartType: 'line',
      option: {
        grid,
        xAxis: {
          type: 'category',
          data: undefined,
          axisTick: {
            // show: false,
            alignWithLabel: true
          },
          axisLine: {
            lineStyle: {
              color: '#c3c3c3'
            }

          },
          axisLabel: {
            color: '#666',
            margin: 18,
            fontSize: 14
          }

        },
        yAxis: [],
        series: []
      }
    }
  },
  computed: {
    ...mapGetters([
      'sidebar'
    ]),
    echartsOptions() {
      const _that = this
      const arr = echartsOptions.map(item => {
        if (item.val === 'avgCptAmount' && _that.adchannelType === 'DISPLAY') {
          return {
            name: 'CPM',
            val: 'avgCpmAmount',
            fix: '$'
          }
        } else if (item.name === '总花费') {
          return { ...item, name: '花费' }
        } else {
          return item
        }
      })

      return arr
    },

    unitTxt() {
      return this.unit === 'RMB' ? '￥' : '$'
    },
    opened() {
      return this.sidebar.opened
    }
  },
  watch: {
    opened: {
      deep: true,
      handler: function(newV, oldV) {
        if (this.dateEchart) {
          const that = this
          this.$nextTick(() => {
            if (this.dateEchart && this.dateEchart.resize) {
              setTimeout(() => {
                that.dateEchart.resize()
              }, 200)
            }
          })
        }
      }
    },

    dateInfo: {
      deep: true,
      handler: function(newV, oldV) {
        if (this.dateInfo.length) {
          this.echartShow = true
          this.$nextTick(() => {
            this.handleDataChange()
          })
        } else {
          this.echartShow = false
        }
      }
    }
  },

  mounted() {
    const el = document.getElementById(this.idName)
    this.dateEchart = this.$echarts.init(el)
    window.addEventListener('resize', () => {
      if (this.dateEchart && this.dateEchart.resize) {
        this.dateEchart.resize()
      }
    })

    this.handleDataChange()
  },
  beforeDestroy() {
    window.removeEventListener('resize', () => {})
  },
  methods: {

    // 设置按钮的背景颜色
    // setBtnType(data) {
    //   const index = this.checkedEO.findIndex(item => {
    //     return item.val === data.val
    //   })
    //   if (index > -1) {
    //     return index === 0 ? 'primary' : 'success'
    //   }
    // },
    // 设置图表显示什么类型的数据
    /*      setEchartShowType(item) {
                                      const index = this.checkedEO.findIndex(v => {
                                        return v.val === item.val
                                      })
                                      if (index === -1) {
                                        this.checkedEO.push({
                                          ...item
                                        })
                                        if (this.checkedEO.length > 2) {
                                          this.checkedEO.splice(0, 1)
                                        }
                                        this.$nextTick(() => {
                                          this.handleDataChange()
                                        })
                                      }
                                    }, */

    // 设置图表的类型
    setEchartType(type) {
      this.dateEchartType = type
      this.$nextTick(() => {
        this.handleDataChange()
      })
    },

    // 图表改变
    handleDataChange() {
      const that = this
      // 循环出来x轴的数据---时间轴;
      const xData = this.dateInfo.map(item => {
        return item.date
      })

      const xAxis = {
        type: 'category',
        data: xData,
        boundaryGap: this.dateEchartType === 'bar',
        axisTick: {
          show: false
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: 'rgba(0, 0, 0, 0.1)',
            // 这里是为了突出显示加上的
            width: 1
          }
        },

        axisLabel: {
          color: '#ACB6C2'
        }
      }

      const EOArr = this.checkedEO.map((item, index) => {
        if (!item) {
          return { ...this.echartsOptions[index],
            name: this.echartsOptions[index].name + index,
            selected: false
          }
        }
        const obj = this.echartsOptions.find(item1 => {
          return item1.val === item
        })
        return { ...obj,
          selected: true
        }
      })

      // 循环出y轴的数据
      const yData = []
      EOArr.forEach((item, index) => {
        if (!item) return false
        let label = '{value}'
        if (item.fix) {
          if (item.fix === '%') {
            label = '{value}' + item.fix
          } else {
            label = this.unitTxt + '{value}'
          }
        }
        const obj = {
          show: item.selected,
          ...yAxisItem,
          min: 0,
          splitNumber: 5,
          name: item.name,
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          },
          axisLabel: {
            formatter: label,
            color: ' rgba(172, 182, 194, 1)'
          }
        }

        if (item.fix === '%') {
          obj.max = 100
          obj.interval = 20
        } else {
          const arr = this.dateInfo.map(v => {
            return v[item.val] * 1
          })

          const max = Math.ceil(Math.max(...arr))
          if (max !== 0) {
            const gutter = max.toFixed(0).toString()
            var length = ''
            if (gutter.length < 3) {
              length = 10
            } else if (gutter.length === 3) {
              length = 100
            } else if (gutter.length === 4) {
              length = 1000
            } else {
              (
                length = 10000
              )
            }

            const end = Math.ceil(max / length) * length
            obj.max = end
            obj.interval = end / 5
          } else {
            obj.max = 100
            obj.interval = 100 / 5
          }
        }

        return yData.push(obj)
      })

      // 循环出seriesData的数据
      var seriesData = []
      EOArr.forEach((item, index) => {
        if (!item) return false
        const data = this.dateInfo.map(v => {
          const num = v[item.val]
          return (num * 1).toFixed(2)
        })

        const obj = {
          name: item.name,
          data,
          type: this.dateEchartType,
          yAxisIndex: index,
          barMaxWidth: 30,
          barMaxWidth: 30,
          boundaryGap: false,
          showSymbol: false,
          splitLine: {
            'show': false
          },
          lineStyle: {
            color: colorList[index] || 'rgba(84, 138, 249, 1)'
          }, // 线条的样式
          itemStyle: {
            color: colorList[index] || 'rgba(84, 138, 249, 1)'
            // opacity: 0 // 为0不会绘制图形拐点消失
          }
        }

        if (this.dateEchartType === 'line') {
          const obj1 = {
            ...obj,
            type: 'line',
            symbol: 'circle',
            symbolSize: 12,
            lineStyle: {
              normal: {
                width: 2,
                color: colorList[index] || 'rgba(84, 138, 249, 1)'
              }

            }, // 线条的样式
            itemStyle: {
              normal: {
                color: colorList[index] || 'rgba(84, 138, 249, 1)',
                borderColor: '#ffffff', // 拐点边框颜色
                borderWidth: 3 // 拐点边框大小
              }
              // opacity: 0 // 为0不会绘制图形拐点消失

            }

          }

          return seriesData.push(obj1)
        } else if (this.dateEchartType === 'lineArea') {
          const obj1 = {
            ...obj,
            type: 'line',
            lineStyle: {
              normal: {
                width: 2,
                color: colorList[index] || 'rgba(84, 138, 249, 1)'
              }

            }, // 线条的样式
            itemStyle: {
              normal: {
                color: colorList[index] || 'rgba(84, 138, 249, 1)',
                borderColor: '#ffffff', // 拐点边框颜色
                borderWidth: 3 // 拐点边框大小
              }
              // opacity: 0 // 为0不会绘制图形拐点消失

            },
            showSymbol: false,
            areaStyle: {},
            emphasis: {
              focus: 'series'
            }
          }

          return seriesData.push(obj1)
        } else {
          return seriesData.push(obj)
        }
      })

      const legend = {
        show: false,
        data: undefined,
        selected: {}
      }
      legend.data = EOArr.map(item => {
        return item.name
      })
      EOArr.forEach(item => {
        legend.selected[item.name] = item.selected
      })

      const options = {
        legend,
        grid,
        xAxis,
        yAxis: yData,
        series: seriesData,

        graphic: {
          type: 'image',
          bottom: 76,
          right: 60,
          style: {
            image: require('@/assets/images/base/logo.png'),
            width: 410,
            height: 66
          }
        },

        tooltip: [{
          trigger: 'axis',
          triggerOn: 'mousemove|click',
          backgroundColor: 'rgba(250, 250, 250, .8)',
          shaowColor: 'rgba(0, 0, 0, .2)',
          textStyle: {
            color: '#666',
            fontSize: '14px'
          },
          formatter: function(params) {
            let str = `<p style="font-size: 12px;margin-bottom:12px"> ${params[0].axisValueLabel}</p>`
            params.forEach(item1 => {
              let fix
              let suffix
              var fixArr = ['花费', '总花费', 'CPT', 'CPA', 'CPM']
              var suffixArr = ['点击率', '转化率']
              if (fixArr.indexOf(item1.seriesName) !== -1) {
                fix = that.unitTxt
              }
              if (suffixArr.indexOf(item1.seriesName) !== -1) {
                suffix = '%'
              }
              str +=
                  `
                  <div class="flex" style="width: 120px;font-size: 12px;">
                    <p>
                    <span style="margin-right: 4px;display: inline-block;border-radius: 50%;height: 10px;width: 10px;background-color: ${item1.color};"></span>
                    <span >${item1.seriesName}</span>
                    </p>
                    <p>

                      <span>${fix || ''}${item1.value}${suffix || ''}</span>
                    </p>
                  </div>
              `
            })

            return str
          },
          axiosPointer: {
            type: 'line',
            lineStyle: {
              type: 'solid',
              color: 'rgba(0, 0, 0, 0.1)'
            }

          }
        }]
      }
      // console.log(JSON.stringify(options),'你好啊啊')

      // 设置盒子
      setTimeout(() => {
        this.dateEchart.resize()
        this.dateEchart.setOption(options, true)
      }, 20)
    },

    resizeWidth() {
      if (this.dateEchart) {
        this.dateEchart.resize()
      }
    },

    // 下载图表
    downloadImg() {
      const picInfo = this.dateEchart.getDataURL({
        type: 'png',
        pixelRatio: 1.5, // 放大两倍下载，之后压缩到同等大小展示。解决生成图片在移动端模糊问题
        backgroundColor: '#fff'
      })
      const elink = document.createElement('a')
      elink.download = '3YData图表'

      elink.style.display = 'none'
      elink.href = picInfo
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
    }

  }
}
</script>

<style lang="scss" scoped="true">
  @import '~@/styles/variables.scss';

  .date-box {
    position: relative;
  }

  .chart-table {
    width: 100% !important;
    overflow: hidden;
  }

  .item-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 12px;
    padding-bottom: 24px;
  }

  .handle-box {
    justify-content: flex-end;

    i {
      font-size: 16px;
      color: rgba(0, 0, 0, 0.45);
      cursor: pointer;
      margin-right: 12px;

      &.active,
      &:hover {
        color: $mainColor1;
      }
    }
  }

  .item-box .lt {
    .el-select {
      width: 120px !important;
      /deep/ .el-input{

        &::after{
          display: inline-block;
          content: '1';
          font-size: 0;
          position: absolute;
          top: 0;
          left: 0;
          height: 32px;
          width: 4px;
          background-color: red;
        }
      }

      /deep/ .el-input__inner {
        border-color: #E0E2E7;
        border-left: 4px solid;
      }

      /deep/.el-input .el-select__caret {
        color: $bodyTxtColor;
        font-size: 12px;
      }
    }

    .el-select.select1 {
      /deep/ .el-input::after{
        background-color: $chartColor1;
      }

      /deep/ .el-input__inner {
        border-left-color: $chartColor1;
      }
    }

    .el-select.select2 {
      /deep/ .el-input::after{
        background-color: $chartColor2;
      }
      /deep/ .el-input__inner {
        border-left-color: $chartColor2;
      }
    }

    >span {
      margin: 0 12px;
      font-family: PingFangSC, sans-serif;
      font-weight: 400;
      font-size: 14px;
      line-height: 14px;
      color: rgba(172, 182, 194, 1);

    }
  }

  .el-select-dropdown__item {
    margin-right: 8px;
    margin-left: 8px;
    &.hover{
      background: transparent;
    }
    &:hover{
      background: #F7F7F9 !important;
    }

    p {
      font-size: 14px;

      i {
        font-weight: 600;
        font-size: 14px;
        margin-right: 8px;
        opacity: 0;
      }

    }

    &.is-disabled {
      color: $isDisabledTxtColor;
    }

    &.selected {
      background: #F7F7F9 !important;
      p {
        span {
          color: $mainColor1 !important;
          font-weight: 400;
        }
      }
    }

    &.select1-op.selected {
      i {
        color: $chartColor1;
        opacity: 1;
      }
    }

    &.select2-op.selected {
      i {
        color: $chartColor2;
        opacity: 1;
      }
    }
  }
</style>
